package org.example.springboot.controller;

import org.example.springboot.common.Result;
import org.example.springboot.entity.User;
import org.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User selected = userService.getUserByAccount(user.getAccount());

        if(selected == null) {
            return Result.error("用户不存在");
        } else if (!selected.getPassword().equals(user.getPassword())) {
            return Result.error("账号或者密码错误");
        }else{
            return Result.success(selected);
        }
    }

    @GetMapping("/page")
    public Result getUsersByPage(@RequestParam("pageNum") int pageNum,
                                 @RequestParam("pageSize") int pageSize,
                                 @RequestParam(value="username",required = false) String username) {
        List<User> userList = userService.getUsersByPage(pageNum, pageSize,username);



        int total = userService.getUserCount(username);

        Map<String, Object> data = new HashMap<>();
        data.put("list", userList);  // 用户列表
        data.put("total", total);    // 总记录数

        return Result.success(data);
    }

    @DeleteMapping("/del/{account}")
    public Result delUser(@PathVariable String account) {
        userService.deleteUserByAccount(account);
        return Result.success("删除成功");
    }

    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {

        User selectUser = userService.getUserByAccount(user.getAccount());
        if(selectUser!=null)
            return Result.error("用户已存在");

        userService.insertUser(user);
        return Result.success("成功添加");
    }

    @PostMapping("/update")
    public Result updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    @PostMapping("/password")
    public Result updatePassword(@RequestBody Map<String, String> payload) {
        String account = payload.get("account");
        String newPassword = payload.get("newPassword");

        userService.updatePassword(account, newPassword);
        return Result.success();
    }
}
